import {ICONS, MENU_TYPE} from "@/common/constant.js";
import {NIcon} from "naive-ui";
import {SettingOutlined} from "@vicons/antd";

/**
 * Get the menu item
 * @param label
 * @param key
 * @param icon
 * @param children
 * @returns {{children, icon, label, type, key}}
 */
export const getMenuItem = (label, key, icon, children) => {
    return {label, key, icon, children}
}

/**
 * Convert tree to menu items
 * @param tree
 * @returns {*|*[]}
 */
export const tree2MenuItems = (tree) => {
    if (tree && tree.length > 0) {
        return tree.map(item => {
            let children = []
            if (item.children && item.children.length > 0) {
                children = tree2MenuItems(item.children)
            }
            if (item.type === MENU_TYPE.CATALOG) {
                return getMenuItem(item.name, item.id, () => renderIcon(ICONS[item.icon]), children)
            }
            if (item.type === MENU_TYPE.MENU) {
                return getMenuItem(item.name, getRouterName(item.component), () => renderIcon(ICONS[item.icon]), undefined)
            }
            return undefined
        }).filter(item => !!item)
    }
    return []
}

/**
 * Get the router
 * @param path
 * @param name
 * @param component
 * @returns {{path, component, children, name}}
 */
export const getRouter = (path, name, component) => {
    return {path, name, component}
}

/**
 * Get the router name
 * @param component
 * @returns {string}
 */
export const getRouterName = (component) => {
    return component.split('/').map(item => item.substring(0, 1).toUpperCase() + item.substring(1)).join('')
}

/**
 * Convert tree to routers
 * @param tree
 */
export const tree2Routers = (tree) => {
    let routers = []
    if (tree && tree.length > 0) {
        tree.forEach(item => {
            if (item.children && item.children.length > 0) {
                routers = routers.concat(tree2Routers(item.children))
            }
            if (item.type === MENU_TYPE.MENU) {
                const path = `/${item.component.replaceAll('/', '-')}`
                const name = getRouterName(item.component)
                routers.push(getRouter(path, name, item.component))
            }
        })
    }
    return routers
}

/**
 * 渲染图标
 * @param icon
 * @returns {VNode}
 */
export const renderIcon = (icon) => {
    return h(NIcon, null, {default: () => h(icon)})
}

/**
 * 对象转数组
 * @param obj
 * @returns {{value: *, key: *}[]}
 */
export const obj2Array = (obj) => {
    return Object.keys(obj)
        .map(key => ({
            key: key,
            value: obj[key]
        }))
}
/**
 * 获取树状结构所有ID
 * @param tree
 * @returns {*[]}
 */
export const getTreeAllIds = (tree) => {
    const ids = [];

    function traverse(node) {
        if (!node) return;

        ids.push(node.id);

        if (node.children) {
            for (const child of node.children) {
                traverse(child);
            }
        }
    }

    for (const rootNode of tree) {
        traverse(rootNode);
    }
    return ids;
}

/**
 * 从树状结构中查找指定ID的父ID集合，包含自身
 * @param tree
 * @param targetId
 * @returns {*[]}
 */
export const findAllParentIdsById = (tree, targetId) => {
    const path = [];

    function traverse(node, currentPath) {
        if (!node) return false;
        // Add the current node ID to the path
        currentPath.push(node.id);
        // Check if the current node is the target node
        if (node.id === targetId) {
            // Copy the current path to the result path
            path.push(...currentPath);
            return true;
        }
        // Traverse the children nodes
        if (node.children) {
            for (const child of node.children) {
                if (traverse(child, currentPath)) {
                    return true;
                }
            }
        }
        // Remove the current node ID from the path if target not found in this path
        currentPath.pop();
        return false;
    }

    for (const rootNode of tree) {
        if (traverse(rootNode, [])) {
            break;
        }
    }
    return path;
}

/**
 * 过滤树形数据
 * @param treeData
 * @param type
 * @param isInclude
 * @returns {*}
 */
export const filterTree = (treeData, type, isInclude = false) => {
    const trees = JSON.parse(JSON.stringify(treeData));
    // 递归过滤函数
    function recursiveFilter(node) {
        // 如果当前节点的 type 是 excludeType，则删除该节点
        if (node.type === type) {
            return isInclude;
        }
        // 如果当前节点有子节点，递归过滤子节点
        if (node.children && node.children.length > 0) {
            node.children = node.children.filter(child => recursiveFilter(child));
            // 如果子节点中有保留的节点，则保留当前节点
            if (node.children && node.children.length === 0) {
                node.children = undefined
            }
        }
        // 否则保留当前节点
        return !isInclude;
    }
    // 过滤根节点，返回新的树形结构
    return trees.filter(root => recursiveFilter(root));
}